import Vue from 'vue'
import VueRouter from 'vue-router'
import http from 'luban-http'

import {
  initVueRoutes,
  createVueRouter,
  isIntoRouteNeedLogin,
  isGetLoginUser,
  fetchLoginUserAndSystemsByAppId,
  fetchAsyncRoutes,
  resetVueRouter,
  isAuthentication
} from './helper'

export default ({ async, type, routes, mode, base }) => {
  Vue.use(VueRouter)

  const vueRoutes = initVueRoutes(Vue, async, type, routes)
  const vueRouter = createVueRouter(VueRouter, vueRoutes, mode, base)
  vueRouter._routes = routes
  vueRouter.beforeEach(async (into, from, next) => {
    http.clearHttpRequestList()
    //  进入的页面是否需要登录
    if (isIntoRouteNeedLogin(into)) {
      const store = vueRouter.app.$options.store
      // 获取登录用户信息和系统列表
      try {
        const appId =
          into.query.appId || process.env.NODE_ENV === 'development' ? '1' : ''
        if (!isGetLoginUser(store)) {
          await fetchLoginUserAndSystemsByAppId(store, appId)
        }
        // 获取异步路由
        if (async && !Vue.$isSuccessFetchAsyncRoutes) {
          const routes = await fetchAsyncRoutes(store, appId)
          resetVueRouter(Vue, vueRouter, type, routes, mode, base)
          next(into.path)
          return
        }
        // 路由权限验证
        if (!isAuthentication(vueRouter, into)) {
          next('401')
          return
        }
        next()
      } catch (error) {
        console.error(error)
      }
    } else {
      next()
    }
  })
  return vueRouter
}
